package com.zsj.Tree;


import org.w3c.dom.Node;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author zsj
 * @Version 1.0
 * @Date 2024/4/13 15:08
 * @Description 二叉树的最小深度
 */
public class TreeMinDeep {

    //后序遍历
    public int minDeep(TreeNode root) {
        if (root == null) return 0;
        int d1 = minDeep(root.left);
        int d2 = minDeep(root.right);
        if (d1 == 0) return d2 + 1;
        if (d2 == 0) return d1 + 1;
        return Math.min(d1, d2) + 1;
    }

    //层序遍历  遍历到的第一个叶子节点的层数 就是最低层数
    public int minDeep2(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            ans++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left == null && poll.right == null) return ans;
                if (poll.right != null) queue.offer(poll.right);
                if (poll.left != null) queue.offer(poll.left);
            }

        }
        return ans;
    }


    public static void main(String[] args) {
        TreeNode treeNode2 = new TreeNode(1
                , new TreeNode(2, new TreeNode(4), null),
                new TreeNode(3, new TreeNode(5), new TreeNode(6)));

        TreeNode treeNode = new TreeNode(1
                , new TreeNode(2, new TreeNode(4), null),
                new TreeNode(3, new TreeNode(5, new TreeNode(7), null),
                        new TreeNode(6)));
//        System.out.println(new TreeMinDeep().minDeep(treeNode2));
//        System.out.println(new TreeMinDeep().minDeep2(treeNode2));

//        System.out.println(new TreeMinDeep().minDeep(treeNode));
//        System.out.println(new TreeMinDeep().minDeep2(treeNode));

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(treeNode);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                System.out.println(poll.val);
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
            }
        }
    }
}
